package com.zziq.mianshi.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zziq.mianshi.common.ErrorCode;
import com.zziq.mianshi.constant.CommonConstant;
import com.zziq.mianshi.exception.BusinessException;
import com.zziq.mianshi.exception.ThrowUtils;
import com.zziq.mianshi.mapper.QuestionBankQuestionMapper;
import com.zziq.mianshi.model.dto.questionBankQuestion.QuestionBankQuestionQueryRequest;
import com.zziq.mianshi.model.entity.Question;
import com.zziq.mianshi.model.entity.QuestionBank;
import com.zziq.mianshi.model.entity.QuestionBankQuestion;
//import com.zziq.mianshi.model.entity.QuestionBankQuestionFavour;
//import com.zziq.mianshi.model.entity.QuestionBankQuestionThumb;
import com.zziq.mianshi.model.entity.User;
import com.zziq.mianshi.model.vo.QuestionBankQuestionVO;
import com.zziq.mianshi.model.vo.UserVO;
import com.zziq.mianshi.service.QuestionBankQuestionService;
import com.zziq.mianshi.service.QuestionBankService;
import com.zziq.mianshi.service.QuestionService;
import com.zziq.mianshi.service.UserService;
import com.zziq.mianshi.utils.SqlUtils;
import io.reactivex.rxjava3.internal.operators.completable.CompletableTimeout;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 题库题目关联服务实现
 */
@Service
@Slf4j
public class QuestionBankQuestionServiceImpl extends ServiceImpl<QuestionBankQuestionMapper, QuestionBankQuestion> implements QuestionBankQuestionService {

    @Resource
    private UserService userService;

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionBankService questionBankService;

    /**
     * 校验数据
     *
     * @param questionBankQuestion
     * @param add                  对创建的数据进行校验
     */
    @Override
    public void validQuestionBankQuestion(QuestionBankQuestion questionBankQuestion, boolean add) {
        ThrowUtils.throwIf(questionBankQuestion == null, ErrorCode.PARAMS_ERROR);

        Long questionId = questionBankQuestion.getQuestionId();
        if (questionId != null) {
            Question question = questionService.getById(questionId);
            ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR, "题目不能为空");
        }

        Long questionBankId = questionBankQuestion.getQuestionBankId();
        if (questionBankId != null) {
            QuestionBank questionBank = questionBankService.getById(questionBankId);
            ThrowUtils.throwIf(questionBank == null, ErrorCode.NOT_FOUND_ERROR, "题库不能为空");
        }

        // todo 暂时无需校验
//        // todo 从对象中取值
//        String title = questionBankQuestion.getTitle();
//        // 创建数据时，参数不能为空
//        if (add) {
//            // todo 补充校验规则
//            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
//        }
//        // 修改数据时，有参数则校验
//        // todo 补充校验规则
//        if (StringUtils.isNotBlank(title)) {
//            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
//        }
    }

    /**
     * 获取查询条件
     *
     * @param questionBankQuestionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionBankQuestion> getQueryWrapper(QuestionBankQuestionQueryRequest questionBankQuestionQueryRequest) {
        QueryWrapper<QuestionBankQuestion> queryWrapper = new QueryWrapper<>();
        if (questionBankQuestionQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = questionBankQuestionQueryRequest.getId();
        Long notId = questionBankQuestionQueryRequest.getNotId();
        Long questionBankId = questionBankQuestionQueryRequest.getQuestionBankId();
        Long questionId = questionBankQuestionQueryRequest.getQuestionId();
        Long userId = questionBankQuestionQueryRequest.getUserId();

        String sortField = questionBankQuestionQueryRequest.getSortField();
        String sortOrder = questionBankQuestionQueryRequest.getSortOrder();
        // todo 补充需要的查询条件
        // 从多字段中搜索

        // 模糊查询

        // JSON 数组查询

        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionBankId), "questionBankId", questionBankId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);

        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取题库题目关联封装
     *
     * @param questionBankQuestion
     * @param request
     * @return
     */
    @Override
    public QuestionBankQuestionVO getQuestionBankQuestionVO(QuestionBankQuestion questionBankQuestion, HttpServletRequest request) {
        // 对象转封装类
        QuestionBankQuestionVO questionBankQuestionVO = QuestionBankQuestionVO.objToVo(questionBankQuestion);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = questionBankQuestion.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionBankQuestionVO.setUser(userVO);
        // 2. 已登录，获取用户点赞、收藏状态
        long questionBankQuestionId = questionBankQuestion.getId();
        User loginUser = userService.getLoginUserPermitNull(request);
//        if (loginUser != null) {
//            // 获取点赞
//            QueryWrapper<QuestionBankQuestionThumb> questionBankQuestionThumbQueryWrapper = new QueryWrapper<>();
//            questionBankQuestionThumbQueryWrapper.in("questionBankQuestionId", questionBankQuestionId);
//            questionBankQuestionThumbQueryWrapper.eq("userId", loginUser.getId());
//            QuestionBankQuestionThumb questionBankQuestionThumb = questionBankQuestionThumbMapper.selectOne(questionBankQuestionThumbQueryWrapper);
//            questionBankQuestionVO.setHasThumb(questionBankQuestionThumb != null);
//            // 获取收藏
//            QueryWrapper<QuestionBankQuestionFavour> questionBankQuestionFavourQueryWrapper = new QueryWrapper<>();
//            questionBankQuestionFavourQueryWrapper.in("questionBankQuestionId", questionBankQuestionId);
//            questionBankQuestionFavourQueryWrapper.eq("userId", loginUser.getId());
//            QuestionBankQuestionFavour questionBankQuestionFavour = questionBankQuestionFavourMapper.selectOne(questionBankQuestionFavourQueryWrapper);
//            questionBankQuestionVO.setHasFavour(questionBankQuestionFavour != null);
//        }
        // endregion

        return questionBankQuestionVO;
    }

    /**
     * 分页获取题库题目关联封装
     *
     * @param questionBankQuestionPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionBankQuestionVO> getQuestionBankQuestionVOPage(Page<QuestionBankQuestion> questionBankQuestionPage, HttpServletRequest request) {
        List<QuestionBankQuestion> questionBankQuestionList = questionBankQuestionPage.getRecords();
        Page<QuestionBankQuestionVO> questionBankQuestionVOPage = new Page<>(questionBankQuestionPage.getCurrent(), questionBankQuestionPage.getSize(), questionBankQuestionPage.getTotal());
        if (CollUtil.isEmpty(questionBankQuestionList)) {
            return questionBankQuestionVOPage;
        }
        // 对象列表 => 封装对象列表
        List<QuestionBankQuestionVO> questionBankQuestionVOList = questionBankQuestionList.stream().map(questionBankQuestion -> {
            return QuestionBankQuestionVO.objToVo(questionBankQuestion);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionBankQuestionList.stream().map(QuestionBankQuestion::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 已登录，获取用户点赞、收藏状态
        Map<Long, Boolean> questionBankQuestionIdHasThumbMap = new HashMap<>();
        Map<Long, Boolean> questionBankQuestionIdHasFavourMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
//        if (loginUser != null) {
//            Set<Long> questionBankQuestionIdSet = questionBankQuestionList.stream().map(QuestionBankQuestion::getId).collect(Collectors.toSet());
//            loginUser = userService.getLoginUser(request);
//            // 获取点赞
//            QueryWrapper<QuestionBankQuestionThumb> questionBankQuestionThumbQueryWrapper = new QueryWrapper<>();
//            questionBankQuestionThumbQueryWrapper.in("questionBankQuestionId", questionBankQuestionIdSet);
//            questionBankQuestionThumbQueryWrapper.eq("userId", loginUser.getId());
//            List<QuestionBankQuestionThumb> questionBankQuestionQuestionBankQuestionThumbList = questionBankQuestionThumbMapper.selectList(questionBankQuestionThumbQueryWrapper);
//            questionBankQuestionQuestionBankQuestionThumbList.forEach(questionBankQuestionQuestionBankQuestionThumb -> questionBankQuestionIdHasThumbMap.put(questionBankQuestionQuestionBankQuestionThumb.getQuestionBankQuestionId(), true));
//            // 获取收藏
//            QueryWrapper<QuestionBankQuestionFavour> questionBankQuestionFavourQueryWrapper = new QueryWrapper<>();
//            questionBankQuestionFavourQueryWrapper.in("questionBankQuestionId", questionBankQuestionIdSet);
//            questionBankQuestionFavourQueryWrapper.eq("userId", loginUser.getId());
//            List<QuestionBankQuestionFavour> questionBankQuestionFavourList = questionBankQuestionFavourMapper.selectList(questionBankQuestionFavourQueryWrapper);
//            questionBankQuestionFavourList.forEach(questionBankQuestionFavour -> questionBankQuestionIdHasFavourMap.put(questionBankQuestionFavour.getQuestionBankQuestionId(), true));
//        }
        // 填充信息
        questionBankQuestionVOList.forEach(questionBankQuestionVO -> {
            Long userId = questionBankQuestionVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionBankQuestionVO.setUser(userService.getUserVO(user));
//            questionBankQuestionVO.setHasThumb(questionBankQuestionIdHasThumbMap.getOrDefault(questionBankQuestionVO.getId(), false));
//            questionBankQuestionVO.setHasFavour(questionBankQuestionIdHasFavourMap.getOrDefault(questionBankQuestionVO.getId(), false));
        });
        // endregion

        questionBankQuestionVOPage.setRecords(questionBankQuestionVOList);
        return questionBankQuestionVOPage;
    }

    /**
     * @Title: batchAddQuestionBankQuestion
     * @Author: Mr·zziq
     * @Date: 2024-12-08 14:02:56
     * @Params: [questionIdList, questionBankId, loginUserId]
     * @Return: void
     * @Description: 批量添加题库题目关联
     */
    @Override
    public void batchAddQuestionBankQuestion(List<Long> questionIdList, Long questionBankId, User loginUser) {
        //题目id校验
        ThrowUtils.throwIf(questionIdList == null || CollUtil.isEmpty(questionIdList),
                ErrorCode.PARAMS_ERROR,
                "题目id不能为空");
        //题库id校验
        ThrowUtils.throwIf(questionBankId == null || questionBankId < 0,
                ErrorCode.PARAMS_ERROR,
                "题库id不合法");
        //校验 添加人id
        ThrowUtils.throwIf(loginUser == null || loginUser.getId() < 0,
                ErrorCode.NOT_LOGIN_ERROR,
                "添加人id不合法");

        //根据questionIdList 查询 question信息是否合法
        LambdaQueryWrapper<Question> lambdaQueryWrapper = Wrappers.lambdaQuery(Question.class)
                .select(Question::getId)
                .in(Question::getId, questionIdList);

        List<Long> validQuestionIdList =
                questionService.listObjs(lambdaQueryWrapper, obj -> (Long) obj);
        ThrowUtils.throwIf(CollUtil.isEmpty(validQuestionIdList),
                ErrorCode.PARAMS_ERROR,
                "所有的题目id不合法");

        //查询 尚未关联目标题库 的题目id
        LambdaQueryWrapper<QuestionBankQuestion> exitedQuestionBankQuestionList =
                Wrappers.lambdaQuery(QuestionBankQuestion.class)
                        .in(QuestionBankQuestion::getQuestionId, validQuestionIdList)
                        .eq(QuestionBankQuestion::getQuestionBankId, questionBankId);
        //查询已经关联的题目id
        Set<Long> exitQuestionIdSet = this.list(exitedQuestionBankQuestionList)
                .stream()
                .map(QuestionBankQuestion::getQuestionId)
                .collect(Collectors.toSet());
        //过滤掉已经关联的题目id
        validQuestionIdList = validQuestionIdList.stream()
                .filter(validQuestionId -> !exitQuestionIdSet.contains(validQuestionId))
                .collect(Collectors.toList());

        //检查题库id是否合法
        QuestionBank questionBank = questionBankService.getById(questionBankId);
        ThrowUtils.throwIf(questionBank == null, ErrorCode.PARAMS_ERROR, "题库不存在/不合法");


        // 自定义线程池,分批处理
        ThreadPoolExecutor customExecutor = new ThreadPoolExecutor(
                20,      // 核心线程数
                50,                 // 最大线程数
                60L,                // 线程空闲存活时间
                TimeUnit.SECONDS,   // 存活时间单位
                new LinkedBlockingQueue<>(10000),  // 阻塞队列容量
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略：由调用线程处理任务
        );

        //保存分批任务
        ArrayList<CompletableFuture> futures = new ArrayList<>();

        //分批处理，避免长事务
        int batchSize = 1000;
        int total = validQuestionIdList.size();
        int endIndex;
        for (int i = 0; i < total; i += batchSize) {
            endIndex = Math.min(i + batchSize, total);
            List<Long> subList = validQuestionIdList.subList(i, endIndex);

            List<QuestionBankQuestion> questionBankQuestionList = subList.stream().map(questionId -> {
                QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
                questionBankQuestion.setQuestionId(questionId);
                questionBankQuestion.setQuestionBankId(questionBankId);
                questionBankQuestion.setUserId(loginUser.getId());
                return questionBankQuestion;
            }).collect(Collectors.toList());

            //获取代理对象
            QuestionBankQuestionService questionBankQuestionServiceProxy
                    = (QuestionBankQuestionServiceImpl) AopContext.currentProxy();

            //异步处理 每批数据
            //创建异步任务
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                //使用代理对象 批量添加关联关系
                questionBankQuestionServiceProxy.batchAddQuestionBankQuestionInner(questionBankQuestionList);
            }, customExecutor).exceptionally(ex -> {
                //捕获异步任务 异常，防止中断其它任务
                log.error("异步任务 批量添加题目到题库时发生异常，错误信息: {}", ex.getMessage());
                return null;
            });
            //将异步任务添加到任务列表
            futures.add(voidCompletableFuture);
        }
        //阻塞等待 所有批次完成任务
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        //关闭线程池
        customExecutor.shutdown();

    }

    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void batchAddQuestionBankQuestionInner(List<QuestionBankQuestion> questionBankQuestionList) {
        //关联题库和题目
        try {
            boolean result = this.saveBatch(questionBankQuestionList);
            if (!result) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "向题库添加题目失败");
            }
        } catch (DataIntegrityViolationException e) {
            log.error("数据库唯一键冲突或违反其他完整性约束，错误信息: {}",
                    e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目已存在于该题库，无法重复添加");
        } catch (DataAccessException e) {
            log.error("数据库连接问题、事务问题等导致操作失败错误信息: {}", e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据库操作失败");
        } catch (Exception e) {
            // 捕获其他异常，做通用处理
            log.error("添加题目到题库时发生未知错误，错误信息: {}", e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "向题库添加题目失败");
        }


    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchRemoveQuestionBankQuestion(List<Long> questionIdList, Long questionBankId) {
        //题目id校验
        ThrowUtils.throwIf(questionIdList == null || CollUtil.isEmpty(questionIdList),
                ErrorCode.PARAMS_ERROR,
                "题目id不能为空");

        //题库id校验
        ThrowUtils.throwIf(questionBankId == null || questionBankId < 0,
                ErrorCode.PARAMS_ERROR,
                "题库id不合法");

        //检查题库id是否合法
        QuestionBank questionBank = questionBankService.getById(questionBankId);
        ThrowUtils.throwIf(questionBank == null, ErrorCode.PARAMS_ERROR, "题库不存在/不合法");

        //关联题库和题目
        for (Long questionId : questionIdList) {
            LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper
                    .eq(QuestionBankQuestion::getQuestionId, questionId)
                    .eq(QuestionBankQuestion::getQuestionBankId, questionBankId);
            boolean res = this.remove(lambdaQueryWrapper);
            ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "删除失败,题目id：" + questionId);
        }
    }


}
